package com.hsource.doctorcenter.service.order.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hsource.common.utils.bean.BeanUtils;
import com.hsource.doctorcenter.conf.dataSource.aspect.SnowflakeIdWorker;
import com.hsource.doctorcenter.domain.clinic.Clinic;
import com.hsource.doctorcenter.domain.doctor.DoctorApi;
import com.hsource.doctorcenter.domain.doctor.DoctorPrice;
import com.hsource.doctorcenter.domain.order.Order;
import com.hsource.doctorcenter.domain.order.OrderApi;
import com.hsource.doctorcenter.domain.order.OrderDoctor;
import com.hsource.doctorcenter.manager.AsyncManager;
import com.hsource.doctorcenter.manager.factory.AsyncFactory;
import com.hsource.doctorcenter.mapper.*;
import com.hsource.doctorcenter.service.order.IOrderService;
import com.hsource.doctorcenter.util.RedisKeyUtil;
import com.hsource.doctorcenter.util.RedisUtil;
import com.hsource.doctorcenter.util.StaticValue;
import com.hsource.doctorcenter.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 订单信息Service业务层处理
 *
 * @author yangyang
 * @date 2020-09-28
 */
@Slf4j
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private ClinicMapper clinicMapper;
    @Autowired
    private DoctorPriceMapper doctorPriceMapper;

    @Autowired
    private OrderDoctorMapper orderDoctorMapper;

    /**
     * 查询订单信息
     *
     * @param id 订单信息ID
     * @return 订单信息
     */
    @Override
    public Order selectOrderById(String id) {
        return orderMapper.selectOrderById(id);
    }



    /**
     * 根据问题Id查看订单问题
     *
     * @param problemId
     * @return
     */
    @Override
    public Order selectOrderByProblemId(Integer problemId){
        return orderMapper.selectOrderByProblemId(problemId);
    }

    /**
     * 查询订单信息列表
     *
     * @param order 订单信息
     * @return 订单信息
     */
    @Override
    public List<Order> selectOrderList(Order order) {
        return orderMapper.selectOrderList(order);
    }

    /**
     * 新增订单信息
     *
     * @param order 订单信息
     * @return 结果
     */
    @Override
    public int insertOrder(Order order) {
        return orderMapper.insertOrder(order);
    }


    /**
     * 订单回调处理
     * @param orderStatus 订单状态
     * @param payOrderId 第三方交易号
     * @param orderId 订单id
     * @param payType 支付类型
     */
    @Override
    public void callBackOrders(String orderStatus,String payOrderId,String orderId,String payType,String payResultJson){
        String orderKeyString = RedisKeyUtil.getRedisKeyString(orderId, RedisKeyUtil.ORDER_LIST);
        if(redisUtil.hasKey(orderKeyString)) {
            Order order = JSONObject.parseObject(JSONObject.toJSONString(redisUtil.get(orderKeyString)), Order.class);
            List<OrderDoctor> orderDoctors = order.getOrderDoctors();
            order.setPayType(payType);
            order.setPayOrderId(payOrderId);
            order.setPayResultJson(payResultJson);
            if (orderStatus.equals("SUCCESS")) {
                //异步创建问题
                order.setPayTime(Calendar.getInstance().getTime());
                order.setPayStatus("D");
            }
            if (orderStatus.equals("REFUND")) {
                order.setPayStatus("T");
                order.setRefundTime(Calendar.getInstance().getTime());
            }
            if (orderStatus.equals("ERROR")) {
                order.setPayStatus("F");
            }
            int i = orderMapper.insertOrder(order);
            if(StringUtils.isNotNull(orderDoctors)&&orderDoctors.stream().count()>0) {
                orderDoctors.stream().forEach(od -> {
                    orderDoctorMapper.insertOrderDoctor(od);
                });
            }
            if (i > 0) {
                if (orderStatus.equals("SUCCESS")) {
                    AsyncManager.me().execute(AsyncFactory.callBackOrdersTimerTask(order));
                }
                redisUtil.del(orderKeyString);
            }
        }
    }

    /**
     * 缓存订单信息
     * @param order 订单对象
     */
    @Override
    public Map<String,Object> redisOrder(Order order,String doctorIds,String consultType){
        String redisKeyString = RedisKeyUtil.getRedisKeyString(order.getUserId(), RedisKeyUtil.IMAGE_TEXT_PROBLEM);
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(1, 1);
        order.setId(String.valueOf(idWorker.nextId()));
        order.setCreateTime(Calendar.getInstance().getTime());
        if(redisUtil.hasKey(redisKeyString)) {
            order.setContent(JSONArray.parse(redisUtil.get(redisKeyString).toString()).toString());
        }
        order.setPayStatus("E");
        Map<String,Object> map=new HashMap<>();
        map.put("orderId",order.getId());
        //查询科室费用
        long orderPrice =999999L;
        Clinic clinic=new Clinic();

        if(consultType.equals("IT")){
            if(StringUtils.isNotBlank(order.getClinicNo())){
                List<Clinic> clinics = clinicMapper.selectClinicList(clinic);
                Clinic c = clinics.stream().findFirst().get();
                map.put("clinicName",c.getClinicName());
                orderPrice = c.getImageTextPrice();
            }
        }
        if(consultType.equals("TH")){
            if(StringUtils.isNotBlank(order.getClinicNo())){
                clinic.setClinicNo(order.getClinicNo());
                List<Clinic> clinics = clinicMapper.selectClinicList(clinic);
                Clinic c = clinics.stream().findFirst().get();
                map.put("clinicName",c.getClinicName());
                orderPrice = c.getPhonePrice();
            }else{
                DoctorPrice doctorPrice=new DoctorPrice();
                doctorPrice.setConsultType(consultType);
                doctorPrice.setDoctorId(doctorIds);
                doctorPrice.setTimeLength(order.getDuration());
                List<DoctorPrice> doctorPrices = doctorPriceMapper.selectDoctorPriceList(doctorPrice);
                if (doctorPrices.stream().count() > 0) {
                    orderPrice=doctorPrices.get(0).getPrice();
                }
            }
        }
        order.setPrice(orderPrice);
        //解析医生信息及费用
        if(StringUtils.isNotBlank(doctorIds)){
            List<DoctorApi> doctorApis = doctorMapper.selectDoctorListByDoctorIds(Convert.toStrArray(doctorIds));
            List<OrderDoctor> orderDoctors=new ArrayList<>();
            Long[] totalPrice={0L};
            doctorApis.stream().forEach(da->{
                OrderDoctor od=new OrderDoctor();
                od.setId(UUID.randomUUID().toString().replaceAll("-",""));
                od.setConsultType(consultType);
                od.setDoctorId(da.getDoctor_id());
                od.setOrderId(order.getId());
                od.setPrice(da.getPrice());
                if(order.getOrderType().equals("DirectedPhone")){
                    od.setDuration(order.getDuration());
                    od.setReservationTime(order.getReservationTime());
                    od.setPrice(order.getPrice());
                }
                if(da.getDoctor_id().equals("0")){
                    od.setPrice(StringUtils.isNoneBlank(StaticValue.SYSTEM_ASSIGNMENT_DOCTOR_PRICE)?Long.parseLong(StaticValue.SYSTEM_ASSIGNMENT_DOCTOR_PRICE):da.getPrice());
                }
                od.setDoctorName(da.getName());
                totalPrice[0]=totalPrice[0]+(od.getPrice());
                orderDoctors.add(od);
            });
            if(orderDoctors.stream().count()>0){
                order.setOrderDoctors(orderDoctors);
                map.put("doctors",orderDoctors);
            }
            order.setPrice(totalPrice[0]);
        }
        map.put("orderTotalPrice",order.getPrice());
        String orderKeyString = RedisKeyUtil.getRedisKeyString(order.getId(), RedisKeyUtil.ORDER_LIST);
        String orderStringKeyString = RedisKeyUtil.getRedisKeyString(order.getId(), RedisKeyUtil.ORDER_LIST_STRING);
        redisUtil.set(orderKeyString,order);
        redisUtil.expire(orderKeyString,10800);


        OrderApi oa=new OrderApi();
        BeanUtils.copyBeanProp(oa,order);
        redisUtil.set(orderStringKeyString,JSONObject.toJSONString(oa));
        return map;
    }
    /**
     * 修改订单信息
     *
     * @param order 订单信息
     * @return 结果
     */
    @Override
    public int updateOrder(Order order) {
        return orderMapper.updateOrder(order);
    }

    /**
     * 删除订单信息对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteOrderByIds(String ids) {
        return orderMapper.deleteOrderByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除订单信息信息
     *
     * @param id 订单信息ID
     * @return 结果
     */
    @Override
    public int deleteOrderById(String id) {
        return orderMapper.deleteOrderById(id);
    }
}
